package cn.ym.org.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.ym.basic.exception.BusinessException;
import cn.ym.basic.service.impl.BaseServiceImpl;
import cn.ym.basic.utils.AjaxResult;
import cn.ym.basic.utils.AssertUtil;
import cn.ym.basic.utils.BaiduAuditUtils;
import cn.ym.basic.utils.PageList;
import cn.ym.org.domain.Employee;
import cn.ym.org.domain.Shop;
import cn.ym.org.domain.ShopAuditLog;
import cn.ym.org.dto.ShopDto;
import cn.ym.org.mapper.EmployeeMapper;
import cn.ym.org.mapper.ShopAuditLogMapper;
import cn.ym.org.mapper.ShopMapper;
import cn.ym.org.query.ShopQuery;
import cn.ym.org.service.ShopService;
import org.assertj.core.internal.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import sun.security.provider.MD5;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;

/**
 * 业务层：店铺
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements ShopService {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void add(Shop shop) {
        AssertUtil.isNotEmpty(shop.getName(),"店铺名称不能为空");
        AssertUtil.isNotEmpty(shop.getTel(),"店铺座机不能为空");
        super.add(shop);
    }

    @Override
    public void update(Shop shop) {
        AssertUtil.isNotEmpty(shop.getName(),"店铺名称不能为空");
        AssertUtil.isNotEmpty(shop.getTel(),"店铺座机不能为空");
        super.update(shop);
    }

    /**
     * 店铺入住
     * @param shop
     * @return
     */
    /**
     *      * 商家入驻逻辑步骤：
     *      * 一：检验
     *      * 1.1.每个参数的空值判断
     *      * 1.2.两次密码不一致校验
     *      * 1.3.该店铺是否已经被入驻过
     *      * 二：入驻业务
     *      * 2.1.保存店铺管理员信息t_employee
     *      * 2.2.保存店铺信息t_shop
     *      * 2.2.将店铺的id更新到t_employee中
     */
    @Transactional
    @Override
    public void settlement(Shop shop) {

        /**
         *  1.空值校验++自动审核
         */
        getCheck(shop);
        /**
         *  2.根据地址和名称判断店铺是否入驻过
         */
        Shop shopTemp=shopMapper.findByNameAndAddress(shop);
        if (shopTemp!=null){
            throw  new BusinessException("店铺已经入驻，请直接登陆！忘记密码请找回密码");
        }
        /**
         *  3.添加管理员信息
         */
        Employee admin = shop.getAdmin();
        String salt = RandomUtil.randomString(32); //生成32位的盐值
        String md5pwd = SecureUtil.md5(admin.getPassword() + salt); //对前端传过来的密码就行 加密加盐
        admin.setSalt(salt);//设置盐值
        admin.setPassword(md5pwd);//现在是加密加盐之后的密码
        admin.setState(0);//激活之后在启用
        /**
         * 4.将管理员的信息添加到数据库，生成自增长的id
         */
        employeeMapper.add(admin);
        //将管理员的id设置到店铺表的adminid
        shop.setAdminId(admin.getId());
        //将店铺信息添加进数据库
        shopMapper.add(shop);
        /**
         *   5.将shop的自增长id设置到employee对象
         */
        admin.setShopId(shop.getId());
        employeeMapper.update(admin);

    }


    /**
     *  1.空值校验
     */
    private void getCheck(Shop shop) {
        if ( StrUtil.isBlank(shop.getName()) || StrUtil.isBlank(shop.getTel())
                || StrUtil.isBlank(shop.getAddress())){
            throw  new BusinessException("店铺信息不能为空");
        }
        if ( StrUtil.isBlank(shop.getAdmin().getUsername()) || StrUtil.isBlank(shop.getAdmin().getPhone())
                || StrUtil.isBlank(shop.getAdmin().getEmail())){
            throw  new BusinessException("管理员信息不能为空");
        }
        //baiduAi智能审核-- //校验店铺名称--logo
        if(!BaiduAuditUtils.TextCensor(shop.getName())){
            throw  new BusinessException("店铺名称不合规");
        }
        if (shop.getLogo()!=null){
            if(!BaiduAuditUtils.ImgCensor("http://123.207.27.208"+ shop.getLogo())){
                throw  new BusinessException("店铺Logo不合规");
            }
        }
    }



    /**
     * 店铺入住-----人工审核通过
     */
    @Transactional
    @Override
    public void pass(ShopAuditLog auditLog) throws MessagingException {
        //查询出是那个店铺
        Shop shop = shopMapper.findOne(auditLog.getShopId());
        if (shop.getState()==2){
            throw  new BusinessException("店铺已经审核过，请查看邮箱激活");
        }
        if (shop.getState()==3){
            throw  new BusinessException("店铺已经激活过，请不要重复操作");
        }
        //1.改店铺的状态1-2
        shopMapper.updateState(auditLog.getShopId(),2);
        //2.记录审核日志
        auditLog.setState(2);
        shopAuditLogMapper.add(auditLog);
        //3.发送邮件：告诉店铺管理员激活邮件使用
        //3.1创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //3.2发送复杂邮件的工具类
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        //3.3发送方
        helper.setFrom("210513347@qq.com");
        helper.setSubject("店铺激活邮件");
        //true - 能够再内容中编写html标签 - 会解析
        //Shop shop = shopMapper.findOne(auditLog.getShopId());
        helper.setText("<h1>你的店铺已经注册!!!</h1><img src='http://123.207.27.208"
                        +shop.getLogo()+"' ><a href='http://127.0.0.1:8080/shop/active/"
                        +shop.getId()+"'>点击该链接激活</a>",
                true);
        Employee employee = employeeMapper.findOne(shop.getAdminId());
        //3.4收件人
        helper.setTo(employee.getEmail());
        javaMailSender.send(mimeMessage);//发送

    }
    /**
     *审核成功---激活邮件
     */
    @Transactional
    @Override
    public void active(Long id) {
        //1.改店铺状态
        Shop shop = shopMapper.findOne(id);
        shop.setState(3);//激活成功
        shopMapper.update(shop);
        //2.修改店铺管理员的状态
        Employee employee = employeeMapper.findOne(shop.getAdminId());
        employee.setState(1);//启用正常使用
        employeeMapper.update(employee);
    }

    /**
     * 图形报表
     * @return
     */
    @Override
    public List<ShopDto> echarts() {
        return shopMapper.echarts();
    }


    /**
     * 店铺入住-----人工审核驳回
     */
    @Transactional
    @Override
    public void reject(ShopAuditLog auditLog) throws MessagingException {
        Shop shop = shopMapper.findOne(auditLog.getShopId());
        if (shop.getState()==3){
            throw  new BusinessException("已经激活了，请不要再重复操作驳回");
        }
        if (shop.getState()==4){
            throw  new BusinessException("已经驳回过，请不要重复操作");
        }
        //1.改店铺的状态1-4
        shopMapper.updateState(auditLog.getShopId(),4);
        //2.记录审核日志
        auditLog.setState(4);
        shopAuditLogMapper.add(auditLog);

        //3.给管理员发送审核失败邮件--重新操作
        //3.发送邮件：告诉店铺管理员激活邮件使用
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //4.发送复杂邮件的工具类
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        //发送方
        helper.setFrom("210513347@qq.com");
        helper.setSubject("店铺审核失败");
        //true - 能够再内容中编写html标签 - 会解析
        //Shop shop = shopMapper.findOne(auditLog.getShopId());
        helper.setText("<h1>你的店铺入驻失败,请点击链接修改之后</h1>" +
                "<a href='http://127.0.0.1:8081/#/shopRegisterEdit/?id="+shop.getId()+"'>重新入驻</a>",true);
        Employee employee = employeeMapper.findOne(shop.getAdminId());
        //收件人
        helper.setTo(employee.getEmail());
        javaMailSender.send(mimeMessage);
    }











}
